// WebSocket连接管理
class WebSocketClient {
    constructor() {
        this.stompClient = null;
        this.connected = false;
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = 5;
    }
    
    connect(userId, onMessageCallback) {
        const socket = new SockJS('/ws');
        this.stompClient = Stomp.over(socket);
        
        this.stompClient.connect(
            { userId: userId },
            (frame) => {
                console.log('WebSocket连接成功:', frame);
                this.connected = true;
                this.reconnectAttempts = 0;
                
                // 订阅用户专属消息队列
                this.stompClient.subscribe(`/user/queue/messages`, (message) => {
                    const messageData = JSON.parse(message.body);
                    onMessageCallback(messageData);
                });
                
                // 订阅会话主题
                this.stompClient.subscribe(`/topic/conversation/${conversationId}`, (message) => {
                    const messageData = JSON.parse(message.body);
                    this.handleConversationMessage(messageData);
                });
            },
            (error) => {
                console.error('WebSocket连接失败:', error);
                this.connected = false;
                this.handleReconnect(userId, onMessageCallback);
            }
        );
    }
    
    handleReconnect(userId, onMessageCallback) {
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
            this.reconnectAttempts++;
            console.log(`尝试重新连接... (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
            
            setTimeout(() => {
                this.connect(userId, onMessageCallback);
            }, 3000 * this.reconnectAttempts); // 指数退避
        }
    }
    
    sendMessage(conversationId, content, messageType = 'text') {
        if (!this.connected) {
            console.error('WebSocket未连接');
            return false;
        }
        
        this.stompClient.send("/app/chat.sendMessage", {}, JSON.stringify({
            conversationId: conversationId,
            content: content,
            messageType: messageType,
            timestamp: Date.now()
        }));
        
        return true;
    }
    
    markAsRead(conversationId, messageId) {
        this.stompClient.send("/app/chat.messageRead", {}, JSON.stringify({
            conversationId: conversationId,
            messageId: messageId
        }));
    }
    
    sendTypingStatus(conversationId, isTyping) {
        this.stompClient.send("/app/chat.typing", {}, JSON.stringify({
            conversationId: conversationId,
            isTyping: isTyping
        }));
    }
    
    disconnect() {
        if (this.stompClient) {
            this.stompClient.disconnect();
        }
    }
}

// 使用示例
const wsClient = new WebSocketClient();

// 连接WebSocket
wsClient.connect('当前用户ID', (messageData) => {
    switch (messageData.type) {
        case 'new_message':
            handleNewMessage(messageData);
            break;
        case 'message_read':
            handleMessageRead(messageData);
            break;
        case 'typing':
            handleTypingStatus(messageData);
            break;
    }
});

// 处理新消息
function handleNewMessage(messageData) {
    // 更新UI显示新消息
    const messageElement = createMessageElement(messageData);
    document.getElementById('message-container').appendChild(messageElement);
    
    // 滚动到底部
    scrollToBottom();
    
    // 播放消息音效
    playMessageSound();
    
    // 更新未读计数
    updateUnreadCount(messageData.conversationId, messageData.unreadCount);
}

// 发送消息
function sendMessage() {
    const content = document.getElementById('message-input').value;
    const conversationId = getCurrentConversationId();
    
    if (content.trim() && wsClient.sendMessage(conversationId, content)) {
        document.getElementById('message-input').value = '';
    }
}